package www.rlicker.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import www.rlicker.model.GroupResource;
import www.rlicker.model.Parameter;
import www.rlicker.model.SysRole;
import www.rlicker.mybatis.Criteria;
import www.rlicker.mybatis.PageResult;
import www.rlicker.service.IGroupResourceService;
import www.rlicker.service.IParameterService;
import www.rlicker.service.ISysRoleService;
import www.rlicker.utils.BaseController;
import www.rlicker.utils.ExportExcel;
import www.rlicker.utils.JsonResult;
import www.rlicker.utils.StringUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "/parameter")
public class ParameterController extends BaseController {

	@Autowired
	private IParameterService service;

	@Autowired
	private IGroupResourceService groupResourceService;

	@Autowired
	private ISysRoleService sysRoleService;

	@RequestMapping("/showlist")
	public String showlist(ModelMap map, HttpServletRequest request) {
		SysRole sysRole = sysRoleService.queryByRoleKey(getUserId(request));
		if (sysRole != null) {
			Criteria<GroupResource> params = new Criteria<GroupResource>();
			params.addParam("resourceIdList", getResourceId(sysRole.getResourceId()));
			params.addParam("parent_resource_id", new Long(request.getParameter("id")));
			params.addParam("status", 0);
			params.addParam("showType", 1);
			List<GroupResource> lists = groupResourceService.queryPageList(params);
			map.put("gpLists", JSONArray.toJSONString(lists));
		}
		map.put("id", request.getParameter("id"));
		return "parameter/parameterList";
	}

	@RequestMapping("/querypage")
	@ResponseBody
	public PageResult queryPage(HttpServletRequest request) {
		Criteria<Parameter> param = new Criteria<Parameter>();
		if (!StringUtil.isNullOrBlank(request.getParameter("pageNumber"))) {
			param.addParam("startIndex", Integer.parseInt(request.getParameter("pageNumber")));
		}
		if (!StringUtil.isNullOrBlank(request.getParameter("pageSize"))) {
			param.addParam("endPage", Integer.parseInt(request.getParameter("pageSize")));
		}
		if (!StringUtil.isNullOrBlank(request.getParameter("word"))) {
			param.addParam("word", request.getParameter("word"));
		}
		if (!StringUtil.isNullOrBlank(request.getParameter("pinyin"))) {
			param.addParam("pinyin", request.getParameter("pinyin"));
		}
		List<Map<String, Object>> list = service.queryPage(param);
		PageResult pageResult = new PageResult();
		pageResult.setTotal(service.queryPageCount(param));
		pageResult.setRows(list);
		return pageResult;
	}

	@RequestMapping("/detail")
	public String detail(String id, String resourceId, ModelMap map) {
		if (!StringUtil.isNullOrBlank(id)) {
			Parameter parameter = service.queryEntity(new Long(id));
			map.put("parameter", parameter);
		}
		map.put("resourceId", resourceId);
		return "parameter/parameterDetail";
	}

	@ResponseBody
	@RequestMapping(value = "/insert", method = { RequestMethod.POST })
	public JsonResult insert(Parameter parameter) {
		JsonResult jr = JsonResult.newInstance();
		String ret = null;
		String pinyin = parameter.getPinyin();
		String[] split = pinyin.split("'");
		parameter.setLength(split.length);
		parameter.setPinyinLength(pinyin.length());
		Criteria<Parameter> param = new Criteria<Parameter>();
		if (!StringUtil.isNullOrBlank(parameter.getWord())) {
			param.addParam("word", parameter.getWord());
		}
		if (!StringUtil.isNullOrBlank(parameter.getPinyin())) {
			param.addParam("pinyin", parameter.getPinyin());
		}
		List<Parameter> pageList = service.queryPageList(param);
		if (pageList.size() == 0) {
			ret = service.insert(parameter);
		}
		return ret == null ? jr.declareSuccess() : jr.declareFailure(ret);
	}

	@ResponseBody
	@RequestMapping(value = "/update", method = { RequestMethod.POST })
	public JsonResult update(Parameter parameter) {
		JsonResult jr = JsonResult.newInstance();
	
		// 先进性删除
	     service.deleteById(parameter.getId());
		// 在进行新增
		String pinyin = parameter.getPinyin();
		String[] split = pinyin.split("'");
		parameter.setPinyinLength(split.length);
		parameter.setDeleteId(parameter.getId().intValue());
		parameter.setId(null);
		String ret = service.insert(parameter);
		
		return ret == null ? jr.declareSuccess() : jr.declareFailure(ret);
	}

	@RequestMapping("/improt")
	public String improt() {
		return "parameter/parameterImprot";
	}

	/**
	 * Exxel导出
	 * 
	 * @param response
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/export")
	public String excelPage(HttpServletRequest request, HttpServletResponse response, String ids, String type) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		String header = "名称:word,拼音:pinyin,数量:count,长度:lenght,基数:baseCount,拼音长度:pinyinLenght";
		String titie = "词汇列表";
		ExportExcel.excel(response, list, titie, header);
		return "success";
	}

	/**
	 * 批量导入
	 * 
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/import")
	@ResponseBody
	public JsonResult importUser(@RequestParam MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) throws IOException, ParseException {
		JsonResult jr = new JsonResult();
		HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
		HSSFSheet sheet = workbook.getSheetAt(0);
		// 总行数
		int trLength = sheet.getLastRowNum();
		trLength = trLength + 1;
		// 4.得到Excel工作表的行
		HSSFRow row = sheet.getRow(0);
		// 总列数
		int tdLength = row.getLastCellNum();
		// 6.得到单元格样式
		List<Parameter> list = new ArrayList<Parameter>();
		for (int i = 1; i < trLength; i++) {
			// 得到Excel工作表的行
			HSSFRow row1 = sheet.getRow(i);
			Parameter parameter = new Parameter();
			for (int j = 0; j < tdLength; j++) {
				// 得到Excel工作表指定行的单元格
				HSSFCell cell1 = row1.getCell(j);
				if (cell1 != null) {
					cell1.setCellType(Cell.CELL_TYPE_STRING);
				}
				if (j == 0) {
					if (cell1 != null) {
						parameter.setWord(cell1.getStringCellValue());
					}
				} else if (j == 1) {
					if (cell1 != null) {
						parameter.setPinyin(cell1.getStringCellValue());
					}
				} else if (j == 2) {
					if (cell1 != null) {
						parameter.setCount(Integer.parseInt(cell1.getStringCellValue()));
					}
				} else if (j == 3) {
					if (cell1 != null) {
						parameter.setLength(Integer.parseInt(cell1.getStringCellValue()));
					}
				} else if (j == 4) {
					if (cell1 != null) {
						parameter.setBaseCount(Integer.parseInt(cell1.getStringCellValue()));
					}
				} else if (j == 5) {
					if (cell1 != null) {
						parameter.setPinyinLength(Integer.parseInt(cell1.getStringCellValue()));
					}
				}
			}
			list.add(parameter);
		}
		jr.declareSuccess();
		jr.addContent("list", list);
		return jr;
	}

	/**
	 * 确认导入
	 * 
	 * @param region
	 * @return
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping(value = "/insertall", method = { RequestMethod.POST })
	public JsonResult insertAll(String staffValue) throws ParseException {
		JsonResult jr = JsonResult.newInstance();
		String ret = null;
		JSONArray array = JSONArray.parseArray(staffValue);
		if (array.size() > 0) {
			for (int i = 0; i < array.size(); i++) {
				JSONObject objects = (JSONObject) array.get(i);
				Parameter parameter = new Parameter();
				parameter.setId(getId());
				if (!StringUtil.isNullOrBlank(objects.getString("word"))) {
					parameter.setWord(objects.getString("word"));
				}
				if (!StringUtil.isNullOrBlank(objects.getString("pinyin"))) {
					parameter.setPinyin(objects.getString("pinyin"));
				}
				if (!StringUtil.isNullOrBlank(objects.getString("count"))) {
					parameter.setCount(Integer.parseInt(objects.getString("count")));
				}
				if (!StringUtil.isNullOrBlank(objects.getString("length"))) {
					parameter.setLength(Integer.parseInt(objects.getString("length")));
				}
				if (!StringUtil.isNullOrBlank(objects.getString("baseCount"))) {
					parameter.setBaseCount(Integer.parseInt(objects.getString("baseCount")));
				}
				if (!StringUtil.isNullOrBlank(objects.getString("pinyinLength"))) {
					parameter.setPinyinLength(Integer.parseInt(objects.getString("pinyinLength")));
				}
				Criteria<Parameter> param = new Criteria<Parameter>();
				if (!StringUtil.isNullOrBlank(parameter.getWord())) {
					param.addParam("word", parameter.getWord());
				}
				if (!StringUtil.isNullOrBlank(parameter.getPinyin())) {
					param.addParam("pinyin", parameter.getPinyin());
				}
				List<Parameter> pageList = service.queryPageList(param);
				if (pageList.size() == 0) {
					ret = service.insert(parameter);
				}
			}
		}
		return ret == null ? jr.declareSuccess() : jr.declareFailure(ret);
	}

}
